package com.cuiyun97.utils;

import com.cuiyun97.domain.po.SetOss;
import com.cuiyun97.service.SetOssService;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

/**
 * ali oss 工具休
 *
 */
@Component
public class AliOssUtil {

    // oss 配置
    @Resource
    private SetOssService ossService;

    public String upload(MultipartFile file) {

        SetOss set = ossService.getLastOne();


        // 获取配置参数
        String endpoint = set.getEndpoint();
        String accessKeyId = set.getAccessKeyId();
        String accessKeySecret = set.getAccessKeySecret();
        String bucketName = set.getBucketName();

        // 获取上传文件的输入流
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));

        // 上传oss
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;

        // 关闭oss
        ossClient.shutdown();

        return url;
    }

}
